﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Windows.Media.Animation;
using MdcService.Static;
using MdcService.Structure;
using Timer = System.Threading.Timer;

namespace MdcMain
{
    public partial class ChartView : Form
    {
        private SynchronizationContext context;
        private MachineValue _machineValue;
        private Timer _timer;
        private string _selectedPath;
        private string _selectedType;
        private double step = 0;


        public ChartView(MachineValue machinevalue)
        {
            InitializeComponent();

            _machineValue = machinevalue;
            context = SynchronizationContext.Current;
            UpdateContent();
            comboBox2.SelectedIndex = 14;
            _timer = new Timer(Callback, null, 0, 1000);

        }

        private void Callback(object state)
        {
            if (!string.IsNullOrEmpty(_selectedPath))
            {
                Add(step, Convert.ToDouble(_machineValue.ValueItems[_selectedPath].Value));
                step += 1;
            }
        }

        public void Add(double x, double y)
        {
            if (_machineValue != null)
            {
                context.Post(i =>
                {
                    try
                    {
                        var ps = chart1.Series[0].Points;
                   
                        ps.AddXY(x, y);
                    }
                    catch (Exception e)
                    {

                    }


                }, null);
            }

        }

        public void UpdateContent()
        {
            comboBox1.Items.Clear();
            _machineValue.ValueItems.Values
                .Where(i => double.TryParse(i.Value, out double d))
                .ForEach(i => comboBox1.Items.Add(i.Path));
            comboBox1.SelectedIndex = 0;
            
            typeof(SeriesChartType).GetFields().Select(i => i.Name).Where(i=>!i.EndsWith("_")).ForEach(i => comboBox2.Items.Add(i));
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            _selectedPath = comboBox1.SelectedItem.ToString();
            chart1.Series[0].Points.Clear();
            step = 0;
            this.Text = _selectedPath;
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            _selectedType = comboBox2.SelectedItem.ToString();
            chart1.Series[0].ChartType = (SeriesChartType) Enum.Parse(typeof(SeriesChartType), _selectedType);
        }
    }
}
